package com.yitong.qicenter.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yitong.qicenter.R;
import com.yitong.qicenter.utils.Config;
import com.yitong.qicenter.utils.network.NetBroadcastReceiver;
import com.yitong.qicenter.utils.network.NetUtil;
//test223
public class MainActivity extends Activity implements View.OnFocusChangeListener, View.OnClickListener, NetBroadcastReceiver.NetChangeListener {
    public static NetBroadcastReceiver.NetChangeListener listener;
    private int netType;//网络类型
    private WebView webview;
    private LinearLayout web_started;
    private LinearLayout webview_error;
    private Button bt_set;
    //Object对象，用来跟JS网页绑定
    private JsInterface JSInterface2 = new JsInterface();
    private Button bt_reload;//重新加载
    private TextView tv_info;//测试信息
    private ProgressBar pb_load;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        setListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideNavigationBar();//隐藏导航栏
    }

    public void initView() {
        hideNavigationBar();//隐藏导航栏
        setContentView(R.layout.activity_main);
        webview = (WebView) findViewById(R.id.webview);
        web_started = (LinearLayout) findViewById(R.id.web_started);
        webview_error = (LinearLayout) findViewById(R.id.webview_error);
        bt_set = (Button) findViewById(R.id.bt_set);

        bt_reload = (Button) findViewById(R.id.bt_reload);
        tv_info = (TextView) findViewById(R.id.tv_info);
        pb_load = (ProgressBar) findViewById(R.id.pb_load);
    }

    public void initData() {
        boolean isNetConnect = checkNet();//初始化时判断有没有网络
        if (isNetConnect) {
            tv_info.append("1初始化时加载网页\n");
            initWebView();
        }
    }

    private void setListener() {
        listener = this;
        bt_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        bt_set.setOnFocusChangeListener(this);
        bt_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                netType = NetUtil.getNetWorkState(MainActivity.this);
                if (!isNetConnect()) {//网络是否连接
                    Toast.makeText(MainActivity.this, "网络异常,无法重新加载!", Toast.LENGTH_LONG).show();
                } else {
                    initWebView();
                }
            }
        });
        bt_reload.setOnFocusChangeListener(this);
    }

    //隐藏导航栏
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("InlinedApi")
    public void hideNavigationBar() {
        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |// 隐藏导航栏
                View.SYSTEM_UI_FLAG_FULLSCREEN | // 隐藏状态栏
                View.SYSTEM_UI_FLAG_IMMERSIVE;
        if (Build.VERSION.SDK_INT >= 19) {
            uiFlags |= 0x00001000;
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }

    private void initWebView() {
        webview.setHorizontalScrollBarEnabled(false);//水平不显示
        webview.setVerticalScrollBarEnabled(false); //垂直不显示
        WebSettings webSettings = webview.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.supportMultipleWindows();  //多窗口
        webSettings.setAppCacheMaxSize(1024 * 1024 * 25);//设置缓冲大小，我设的是8M
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setSavePassword(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSaveFormData(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webview.addJavascriptInterface(JSInterface2, "JavascriptInterface");
        JSInterface2.setExitClientClickListener(new webExitClick());//退出按钮事件

        webview.loadUrl(Config.BASEURL);
        showWebViewLoad();
    }

    private void showWebViewLoad() {
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                return true;
            }

            //当开始载入页面的时候调用
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                //隐藏无网络布局
                webview_error.setVisibility(View.GONE);
                //显示加载网页中布局
                web_started.setVisibility(View.VISIBLE);

            }

            /*初始加载完成*/
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //隐藏加载网页中布局
                web_started.setVisibility(View.GONE);
            }

            /*加载失败时*/
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.e(TAG, "onReceivedError: ====errorCode:" + errorCode + " description:" + description + " failingUrl:" + failingUrl);
            }
        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 50) {
                    //隐藏加载网页中布局
                    web_started.setVisibility(View.GONE);
                }
                if (newProgress > 90) {
                    pb_load.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    pb_load.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pb_load.setProgress(newProgress);//设置进度值
                }
            }
        });
    }

    private static final String TAG = "MainActivity";

    /***
     * 防止WebView加载内存泄漏
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        webview.removeAllViews();
        webview.destroy();

    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            switch (v.getId()) {
                case R.id.bt_set:
                    bt_set.setBackgroundResource(R.drawable.case_blue_bg);
                    bt_set.setTextColor(Color.parseColor("#ffffff"));
                    break;
                case R.id.bt_reload:
                    bt_reload.setBackgroundResource(R.drawable.case_blue_bg);
                    bt_reload.setTextColor(Color.parseColor("#ffffff"));
                    break;
            }
        } else {
            switch (v.getId()) {
                case R.id.bt_set:
                    bt_set.setBackgroundResource(R.drawable.case_blue_bg2);
                    bt_set.setTextColor(Color.parseColor("#0064b2"));
                    break;
                case R.id.bt_reload:
                    bt_reload.setBackgroundResource(R.drawable.case_blue_bg2);
                    bt_reload.setTextColor(Color.parseColor("#0064b2"));
                    break;

            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {


        }
    }
    /**
     * 初始化时判断有没有网络
     */
    public boolean checkNet() {
        this.netType = NetUtil.getNetWorkState(MainActivity.this);
        if (!isNetConnect()) {
            //显示无网络布局
            webview_error.setVisibility(View.VISIBLE);
            //隐藏加载网页中布局
            web_started.setVisibility(View.GONE);
            Toast.makeText(this, "网络异常，请检查网络!", Toast.LENGTH_SHORT).show();
        }
        return isNetConnect();
    }

    /**
     * 网络变化之后的类型
     */
    @Override
    public void onChangeListener(int netMobile) {
        this.netType = netMobile;
        if (!isNetConnect()) {

            Toast.makeText(this, "网络异常，请检查网络!", Toast.LENGTH_SHORT).show();
            //显示无网络布局
            webview_error.setVisibility(View.VISIBLE);
            //隐藏加载网页中布局
            web_started.setVisibility(View.GONE);
        } else {

            tv_info.append("2网络恢复正常时加载网页\n");
            Toast.makeText(this, "网络恢复正常!", Toast.LENGTH_SHORT).show();
            //初始化webview
            initWebView();
        }
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netType == 2) {//以太网
            return true;
        } else if (netType == 1) {//无线网络
            return true;
        } else if (netType == 0) {//移动网络
            return true;
        } else if (netType == -1) {//无网络
            return false;
        }
        return false;
    }



    //单机返回按键的时候操作
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onExitClick();
        }
        return false;
    }
    //退出页面警告对话框
    void onExitClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("确定要离开当前系统吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // 这里添加点击确定后的逻辑
            }
        });
        builder.create().show();
    }
    //退出按钮
    class webExitClick implements JsInterface.doExitClientClickListener {
        @Override
        public void doExitClickEnvent() {
            //跳转到我的进货页面
            onExitClick();
        }
    }
}
